package com.woniu.zsd.user.config;




import com.woniu.zsd.common.util.RedisKey;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;

@Data
public class RabbitMQCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback{
    private StringRedisTemplate stringRedisTemplate;
    private RabbitTemplate rabbitTemplate;

    /**
     *
     * @param correlationData 消息id
     * @param b 消息投递状态
     * @param s 消息投递失败原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        System.out.println("消息id"+correlationData.getId()+"  进入队列"+"投递状态"+b+" "+s);
        if (b){
            //删除redis中的消息id
            stringRedisTemplate.delete(RedisKey.rabbitmqMessageIdKey(correlationData.getId()));
        }else {
            //重试
            Map<Object, Object> messageMap = stringRedisTemplate.opsForHash().entries(RedisKey.rabbitmqMessageIdKey(correlationData.getId()));
            String exchange = messageMap.get("exchange").toString();
            String routingKey = messageMap.get("routingKey").toString();
            String message = messageMap.get("message").toString();
            rabbitTemplate.convertAndSend(exchange,routingKey,message,correlationData);
            //记录重试次数
        }
    }

    /**
     *
     * @param message
     * @param i 异常代码
     * @param s 异常原因
     * @param exchange
     * @param routingKey
     */
    @Override
    public void returnedMessage(Message message, int i, String s, String exchange, String routingKey) {
        byte[] body = message.getBody();
        CorrelationData correlationData = new CorrelationData(message.getMessageProperties().getMessageId());
        rabbitTemplate.convertAndSend(exchange,routingKey,body,correlationData);
    }
}
